package com.i2works.smartluolong.utils.common;

import com.google.common.io.Files;
import com.i2works.smartluolong.utils.base.DateConstant;
import com.i2works.smartluolong.utils.base.GlobalConstant;
import com.i2works.smartluolong.utils.base.MsgEnum;
import com.xiaoleilu.hutool.util.RandomUtil;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.Serializable;

/**
 * 上传工具类
 *
 * @author Liu Yutao
 * @className Upload
 * @email koal@vip.qq.com
 * @date 2016/2/12 22:30
 */

public class UploadUtil implements Serializable {


    private String dirPath = null;  //默认物理路径 D:/temp/static/upload/
    private String webPath = null;  //默认访问路径 files/201704/
    private String subPath = null;  //物理路径的子目录 files/、poster/

    private String allowSuffix = GlobalConstant.suffix.FILES;    //默认图片
    private long allowSize = 100 * 1024 * 1024;                  //允许文件大小
    private String fileName;                                     //文件名
    private String fileSize;                                     //文件大小（MB）
    private String fileUrl;                                      //文件url路径


    private String getDirPath() {
        return dirPath;
    }

    public void setDirPath(String dirPath) {
        this.dirPath = dirPath;
    }

    public String getWebPath() {
        return webPath;
    }

    private void setWebPath(String webPath) {
        this.webPath = webPath;
    }

    private String getSubPath() {
        return subPath;
    }

    public void setSubPath(String subPath) {
        this.subPath = subPath;
    }

    private long getAllowSize() {
        return allowSize;
    }

    public void setAllowSize(long allowSize) {
        this.allowSize = allowSize;
    }

    public String getFileName() {
        return fileName;
    }

    private void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFileSize() {
        return fileSize;
    }

    private void setFileSize(String fileSize) {
        this.fileSize = fileSize;
    }

    public String getFileUrl() {
        return fileUrl;
    }

    private void setFileUrl(String fileUrl) {
        this.fileUrl = fileUrl;
    }

    private String getAllowSuffix() {
        return allowSuffix;
    }

    public void setAllowSuffix(String allowSuffix) {
        this.allowSuffix = allowSuffix;
    }

    /**
     * 单个文件上传
     *
     * @param file      文件
     * @param filesType 上传的类型
     */
    public void upload(MultipartFile file, Integer filesType) throws Exception {
        try {
            //文件服务器的相对路径 images/201610/01/
            String destDir = getSubPath() + DateUtils.get(DateConstant.YYYYMM) + "/" + DateUtils.get(DateConstant.DAY) + "/";
            //后缀
            String suffix = Files.getFileExtension(file.getOriginalFilename());
            //原名
            String baseName = Files.getNameWithoutExtension(file.getOriginalFilename());
            //判断后缀
            checkSuffix(suffix, filesType);
            //判断文件大小
            if (file.getSize() > getAllowSize()) {
                throw new Exception(MsgEnum.UPLOAD_FILE_SIZE_ERROR.getMsg());
            }
            //创建完整路径 d:/file.server.com/stills/201610/
            File destFile = new File(getDirPath() + destDir);
            if (!destFile.exists()) {
                destFile.mkdirs();
            }
            //获取上传文件的名称：文件用原名+随机.jpg
//            String resultFileName = baseName + "_" + RandomUtil.randomNumbers(10) + "." + suffix.toLowerCase();
//            if (filesType.equals(GlobalConstant.fileType.FILES)) {
//                resultFileName = baseName + "." + suffix.toLowerCase();
//            } else {
//                resultFileName = DateUtils.get(DateConstant.ALLS_SIMPLE) + "." + suffix.toLowerCase();
//            }

            String resultFileName = RandomUtil.simpleUUID() + "." + suffix.toLowerCase();
            //判断本地文件是否存在
            if (new File(destFile.getAbsoluteFile() + "/" + resultFileName).exists()) {
                resultFileName = baseName + "_" + System.currentTimeMillis() + "." + suffix.toLowerCase();
            }
            //实例化文件到磁盘
            File uploadFile = new File(destFile.getAbsoluteFile() + "/" + resultFileName);
            file.transferTo(uploadFile);
            uploadFile.createNewFile();
            //判断是否为图片,图片进行压缩,宽度800,高度自适应
            if (GlobalConstant.fileType.IMAGE.equals(filesType)) {
                String targetImageName = RandomUtil.simpleUUID() + "." + suffix.toLowerCase();
                File compressImage = imageCompress(uploadFile, targetImageName);
                //计算大小
                setFileSize(StrUtil.convertFileSize(compressImage.length()));
                //返回相对路径
                setFileUrl(destDir + compressImage.getName());
                //返回文件名
                setFileName(compressImage.getName());
            } else {
                //计算大小
                setFileSize(StrUtil.convertFileSize(file.getSize()));
                //返回相对路径
                setFileUrl(destDir + resultFileName);
                //返回文件名
                setFileName(resultFileName);
            }

            //返回相对路径
            setWebPath(destDir);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            throw new Exception(e);
        }
    }


    /**
     * 图片压缩
     */
    private static File imageCompress(File sourceImageFile, String targetImageName) {
        File targetImageFile = new File(sourceImageFile.getParent() + File.separatorChar + targetImageName);
        ImageUtil.scaleWithWidth(sourceImageFile, targetImageFile, 800);
        //删除原图片
        sourceImageFile.delete();
        return targetImageFile;
    }

    /**
     * 后缀检测
     *
     * @param suffix 后缀
     * @param type   文件类型
     */
    private void checkSuffix(String suffix, Integer type) throws Exception {
        Integer length;
        //如果是文件
        if (GlobalConstant.fileType.FILES.equals(type)) {
            length = GlobalConstant.suffix.FILES.indexOf(suffix.toLowerCase());
        } else {
            length = GlobalConstant.suffix.IMAGE.indexOf(suffix.toLowerCase());
        }
        if (length == -1) {
            throw new Exception(MsgEnum.UPLOAD_FILE_TYPE_ERROR.getMsg());
        }
    }


}
